<?php

	if (substr($_SERVER['SCRIPT_FILENAME'], 0, 1) != "/") {
		die("please call script with absolute path!\n");
	}



	/* reload firewall */


	$x = exec("sudo /etc/init.d/wlan_firewall 2>&1", $lines);
	
	if ($x != "") {
		foreach ($lines as $line) {
			echo $line."\n";
		}
	}
	
	
	
	/* save log */

	$root = substr($_SERVER['SCRIPT_FILENAME'], 0, -12);

	$logFilename = date("d.m.Y", time()-60*60*24);
	
	if (!file_exists($root."data/logs/".$logFilename)) {

		/* save current log */
		$copy = copy($root."data/log", $root."data/logs/".$logFilename);
		
		if ($copy) {
			
			//flush current log file
			file_put_contents($root."data/log", "");
			
			
				/* update domain stats */
				
				$db = new SQLiteDatabase($root.'data/domains');

				/* check if table exists */
				$result = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='domains'");
				if ($result->numRows() == 0) {

					/* create new table */
					$query = "
						CREATE TABLE domains (
							id					INTEGER			NOT NULL,
							domain				VARCHAR(250)	NOT NULL,
							url					VARCHAR(250)	NOT NULL,
							counter				INTEGER			NOT NULL,
							month				VARCHAR(7)		NOT NULL,
							CONSTRAINT domains_PK  PRIMARY KEY (id)
						);
					";
					$createTable = $db->query($query);

					if ($createTable === false) {
						die("ERROR: unable to create database table 'domains'!\n");
					}

				}




				//$db->query("DELETE FROM domains");


				$logFile = fopen($root."data/logs/".$logFilename, "r");

				if ($logFile) {

						while (!feof($logFile)) {

							$line = fgets($logFile, 4096);

							if (strpos($line, "LOGIN ") === false AND strpos($line, "http://") !== false) {

								$url = substr($line, strpos($line, "http://"));
								$url = substr($url, 0, strpos($url, " "));

								$domain = substr($url, 7);
								$domain = substr($domain, 0, strpos($domain, "/"));

								if (!preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/is', $domain)) {

									/* domain is real domain, not IP address */
									$domainParts = explode(".", $domain);
									$domain = $domainParts[count($domainParts)-2].".".$domainParts[count($domainParts)-1];

								}

								$check = $db->singleQuery("SELECT id FROM domains WHERE domain = '".$domain."' AND month = '".date("m.Y")."' LIMIT 1");
								if (!$check) {

									/* new domain */	
									$db->query("INSERT INTO domains (domain, url, counter, month) VALUES ('".$domain."', '".$url."', 1, '".date("m.Y")."')");

								} else {

									/* known domain -> increase counter */
									$db->query("UPDATE domains SET counter = counter+1 WHERE domain = '".$domain."' AND month = '".date("m.Y")."'");

								}

							}

						}

					fclose($logFile);

				} else {
					die("error opening log file!\n");
				}
			
			
		} else {
			echo "ERROR: failed to copy '".$root."data/log' -> '".$root."data/logs/".$logFilename."'\n";
		}
		
	} else echo "exists!\n";
	

?>
